package org.jmc.refmanager.web.wicket.provider;

import java.util.Iterator;

import org.apache.wicket.extensions.markup.html.repeater.util.SortParam;
import org.apache.wicket.extensions.markup.html.repeater.util.SortableDataProvider;
import org.apache.wicket.injection.web.InjectorHolder;
import org.apache.wicket.model.IModel;
import org.apache.wicket.spring.injection.annot.SpringBean;
import org.jmc.refmanager.domain.dao.QueryParam;
import org.jmc.refmanager.domain.model.OrgUnit;
import org.jmc.refmanager.domain.service.OrgUnitManager;
import org.jmc.refmanager.web.wicket.model.ServiceModel;

/**
 * 
 *
 */
public class SortableServiceDataProvider extends SortableDataProvider<OrgUnit> {
	private static final long serialVersionUID = 1L;
	
	@SpringBean(name="orgUnitManager")
	private OrgUnitManager orgUnitManager;

	private QueryParam<OrgUnit> queryParameters;
	private String matricule;
	
	/**
	 * 
	 */
	public SortableServiceDataProvider(QueryParam<OrgUnit> params, String requesterUsername) {
		super();
		InjectorHolder.getInjector().inject(this);
		this.queryParameters = params;
		this.matricule = requesterUsername;
	}

	@Override
	public Iterator<? extends OrgUnit> iterator(int first, int count) {
		SortParam sortParam = getSort();
		if (this.queryParameters == null) {
			this.queryParameters = new QueryParam<OrgUnit>();
		}
		
		if (sortParam != null) {
			this.queryParameters.setSortAsc(sortParam.isAscending());
			this.queryParameters.setSortPropertyName(sortParam.getProperty());
		}
		
		this.queryParameters.setFirst(first);
		this.queryParameters.setCount(count);
		
		// Appel e la couche de service
		return orgUnitManager.findScopedServices(queryParameters, matricule).iterator();
	}

	@Override
	public IModel<OrgUnit> model(OrgUnit service) {
		return new ServiceModel(service);
	}

	@Override
	public int size() {
		if (queryParameters.getCriteriaExample() == null) {
			return 0;
		} else {
			// Appel e la couche de service
			return orgUnitManager.countScopedServices(queryParameters, matricule);
		}
	}

}
